from reader import GoogleReader
from const import CONST
from userconfig import USER
from api import Twitter
from api import TwitterError
import bitly
import time
import random
import urllib
import traceback
import cPickle as p

def ErrorProcess(err):
    print "-------- Twitter Error --------"
    print "Code: %d" % (err.code)
    print "Error: %s" % (err.msg)
    print "-------------------------------"

def LoadMap(filename):
    try:
        f = open(filename)
        obj = p.load(f)
        f.close()
        return obj
    except Exception,e:
        print e    
        return

def main():

    totalerr = 0    
    #twitter = Twitter(token=LoadMap('access_token'))
    twitter = Twitter(email=USER.twuser,password=USER.twpass,domain="apiproxy.appspot.com/api",protocol="http")
    #fanfou = Twitter(email="junytang@gmail.com",password="qazwsx",domain="api.fanfou.com",protocol="http")
    
    gr = GoogleReader()
    gr.identify(USER.gruser,USER.grpass)
    gr.login()

    while True:
        try:
	    
	    tmp = []
            feeds = gr.get_subscription_list()
            for entry in feeds['subscriptions']:
                tmp.append(entry['categories'][0]['label'])
            labels = list(set(tmp))
    
	    for label in labels:
	   	
		found = 0
		print "Refresh..."
		url = urllib.quote_plus(label.encode('utf-8'))	
		xmlfeed = gr.get_feed(feed=CONST.ATOM_PREFIXE_LABEL+url,exclude_target=CONST.ATOM_STATE_READ,count=1)
		
		for entry in xmlfeed.get_entries():
		    
		    if (cmp(label,'quote') !=0):
                        if (cmp(label,'english') !=0):
                            message = "#%s %s - %s" % (label, entry['title'], bitly.shorten(entry['link']))
                        else:
                            message = "%s - %s" % (entry['title'], bitly.shorten(entry['link']))
		    else:
			message = "#%s %s" % (label, entry['title'])

                    print "Add: %s - %s " % (label, message)
		    gr.set_read(entry['google_id'])

                    if (len(message) <= 140):
                        text = unicode(message).encode('utf-8')
                        twitter.statuses.update(status=text)
                        #try:
                        #    #fanfou.statuses.update(status=text)
                        #except Exception,e:
                        #    print "Fanfou failed...", e
                        #    exstr = traceback.format_exc()  
                        #    print exstr
                        #    pass
                        totalerr = 0
                    else:
                        print "Text must be less than or equal to 140 characters."
 
                    mhour = time.localtime().tm_hour
                    if (mhour >= 0 and mhour <= 6):
                        time.sleep(28800)
                    else:
                        found = 1
                        time.sleep( 2 * (2700 + random.randint(0,900)) * 2)
            
	    if (found == 0):
		time.sleep(600)
		
        except TwitterError,e:
            if (totalerr < 3): totalerr = totalerr + 1
            ErrorProcess(e)
            time.sleep(1000 * totalerr)
            continue	    
        except Exception,e:
            if (totalerr < 3): totalerr = totalerr + 1
	    print "Connection failed...", e
            exstr = traceback.format_exc()  
            print exstr   	    
            time.sleep(1000 * totalerr)
	    continue

if __name__=='__main__' :
    main()
